package com.zhf.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author: ZhaoHuanfeng
 * @Date: 2020/10/25 17:29
 */
@WebFilter(filterName = "MyFilter",urlPatterns = "/*")
public class MyFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest httpServletRequest=(HttpServletRequest) req;
        HttpSession session = httpServletRequest.getSession();
        Object user = session.getAttribute("user");

        String servletPath=httpServletRequest.getServletPath();

        //对css和js文件不拦截
        if (servletPath.endsWith(".css")||servletPath.endsWith(".js")){
            chain.doFilter(req,resp);
            //若无用户登录则拦截并跳转到登录页面
        }else if (user==null&&!servletPath.contains("login")){
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }else if (user!=null&&servletPath.contains("login")){
            //若有用户登录则拦截并跳转到菜单页面
            req.getRequestDispatcher("menu.jsp").forward(req,resp);
        }else {
            //其他情况暂时不拦截
            chain.doFilter(req,resp);
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
